package com.bigstar.lolkor;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RankingDialog extends Dialog implements OnClickListener {

	private static String strBBUrl = "http://www.ghdnjs9012.com/";

	TextView tv_ranking_text;
	EditText et_name;
	Button btn_regist;
	Button btn_cancel;

	long gameTime;
	int stage;
	int type;

	Context context;

	public RankingDialog(Context context, int type, long gameTime, int stage) {
		super(context);
		this.context = context;
		this.gameTime = gameTime;
		this.stage = stage;
		this.type = type;
		setContentView(R.layout.ranking_dialog);
		tv_ranking_text = (TextView) findViewById(R.id.ranking_text);
		et_name = (EditText) findViewById(R.id.et_name);
		btn_regist = (Button) findViewById(R.id.btn_ranking_regist);
		btn_regist.setOnClickListener(this);
		btn_cancel = (Button) findViewById(R.id.btn_ranking_cancel);
		btn_cancel.setOnClickListener(this);
		SharedPreferences pref = context.getSharedPreferences("pref",
				Activity.MODE_PRIVATE);
		if (type == 0) {
			long high_time = pref.getLong("card_game_time", 0);
			int sec = (int) (high_time / 1000);
			int mil_sec = (int) (high_time % 1000);
			int cur_sec = (int) (gameTime / 1000);
			int cur_mil_sec = (int) (gameTime % 1000);
			if (high_time <= gameTime && high_time != 0) {
				tv_ranking_text.setText("당신의 카드게임 타임은\r\n 지금 시간 : " + cur_sec
						+ "." + cur_mil_sec + "초\r\n최단 시간 : " + sec + "."
						+ mil_sec + "초\r\n지금 시간을 랭킹등록하시겠습니까?");
			} else {
				SharedPreferences.Editor editor = pref.edit();
				editor.putLong("card_game_time", gameTime);
				editor.commit();
				tv_ranking_text.setText("카드게임 최단 시간 달성!\r\n 지금 시간 : " + cur_sec
						+ "." + cur_mil_sec + "초\r\n이전 최단 시간 : " + sec + "."
						+ mil_sec + "초\r\n지금 시간을 랭킹등록하시겠습니까?");
			}
		} else {
			int high_stage = pref.getInt("quiz_game_stage", 1);
			if (high_stage < stage) {
				SharedPreferences.Editor editor = pref.edit();
				editor.putInt("quiz_game_stage", (stage-1));
				editor.commit();
				tv_ranking_text.setText("퀴즈게임 최고 기록 달성!\r\n 지금 문제 : " + stage
						+ "문제\r\n이전 최고 문제 : " + high_stage
						+ "문제\r\n지금 기록을 랭킹등록하시겠습니까?");
			} else {
				tv_ranking_text.setText("퀴즈게임 최고 기록 달성!\r\n 지금 문제 : " + stage
						+ "문제\r\n이전 최고 문제 : " + high_stage
						+ "문제\r\n지금 기록을 랭킹등록하시겠습니까?");
			}
		}
		Random r = new Random();
		String user_id = pref.getString("game_user_id", "");
		if (user_id != null && !user_id.equals("")) {
			et_name.setText(user_id);
		}
	}

	@Override
	public void onBackPressed() {
		if (context instanceof CardTurn) {
			((CardTurn) context).finish();
		} else if (context instanceof Quiz) {
			((Quiz) context).finish();
		}
	}

	@Override
	public void dismiss() {
		if (context instanceof CardTurn) {
			((CardTurn) context).finish();
		} else if (context instanceof Quiz) {
			((Quiz) context).finish();
		}
		super.dismiss();
	}

	@Override
	public void cancel() {
		if (context instanceof CardTurn) {
			((CardTurn) context).finish();
		} else if (context instanceof Quiz) {
			((Quiz) context).finish();
		}
		super.cancel();
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_ranking_cancel) {
			this.cancel();
		} else if (v.getId() == R.id.btn_ranking_regist) {
			if (et_name.getText().toString() == null
					|| et_name.getText().toString().equals("")) {
				Toast.makeText(context, "랭킹을 등록할 이름을 입력하세요.",
						Toast.LENGTH_SHORT).show();
				return;
			}
			SharedPreferences pref = context.getSharedPreferences("pref",
					Activity.MODE_PRIVATE);
			SharedPreferences.Editor editor = pref.edit();
			editor.putString("game_user_id", et_name.getText().toString());
			editor.commit();
			if (type == 0) {
				if (gameTime > 180000) {
					Toast.makeText(context, "3분 안으로 랭킹등록좀 -ㅅ-", Toast.LENGTH_SHORT).show();
					return;
				}
			}else{
				if (stage < 10) {
					Toast.makeText(context, "10스테이지는 넘고 랭킹등록좀 -ㅅ-", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			regdit();
			Toast.makeText(context, "등록 완료~", Toast.LENGTH_SHORT).show();
			this.cancel();
		}
	}

	public void regdit() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost get = new HttpPost();
			get.setURI(new URI(strBBUrl + "/RankingRedit.php"));

			List<NameValuePair> params = new ArrayList<NameValuePair>();

			params.add(new BasicNameValuePair("uuid", Utils.GetDevicesUUID(context)));
			params.add(new BasicNameValuePair("user_name", ""+ et_name.getText().toString()));
			params.add(new BasicNameValuePair("game_type", "" + type));
			params.add(new BasicNameValuePair("game_time", "" + gameTime));
			params.add(new BasicNameValuePair("stage", "" + (stage-1)));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			get.setEntity(entity);

			HttpResponse resp = client.execute(get);
			BufferedReader br = new BufferedReader(new InputStreamReader(resp
					.getEntity().getContent()));
			String str = null;
			StringBuilder sb = new StringBuilder();

			while ((str = br.readLine()) != null) {
				sb.append(str).append("\n");
			}
			br.close();
			Log.i("sb", sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
